<template>
  <el-dialog :title="$t('constant.tsl.BATCH_ADD_TSL')" :close-on-click-modal="false" :visible.sync="addBatchDeviceShow">
    <el-form :inline-message=true ref="addBatchDeviceForm" :model="form" :rules="formRules" label-width="120px">
      <el-row>
        <el-col>
          <el-form-item :label="$t('constant.tsl.UPLOAD_TSL')" props="fileId">
            <el-upload
              class="upload-demo"
              ref="upload"
              action="doUpload"
              accept=".json"
              :limit="1"
              :file-list="fileList"
              :on-change="fileChange"
              :before-upload="beforeUpload">
              <el-button size="small" slot="trigger"  type="primary" plain>选取文件</el-button>
              <el-button size="small"  type="primary" name="downloadfile" @click="downloadTemp()" plain>下载模板</el-button>
              <div slot="tip" class="el-upload__tip">只能上传json文件，且不超过5MB</div>
              <div slot="tip" class="el-upload-list__item-name" v-show="fileShow">{{fileName}}</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" type="close" @click="addBatchDeviceShow = false">{{$t('button.CLOSE')}}</el-button>
      <el-button size="small" type="save" @click="save" :loading="addBatchDeviceLoading">{{$t('button.SAVE')}}</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {DataMainApi, Status} from "../ApiConstant";

    export default {
        name: "TslBatchAdd",
      data(){
        var changeFile = (rule, value, callback) => {
          if(null==this.files){
            callback(new Error("请上传文件"));
          }else{
            callback();
          }
        };
          return{
            type:"5",
            addBatchDeviceShow:false,
            fileList: [],
            fileShow: false,
            addBatchDeviceLoading: false,
            downloadFile: null,
            fileName:null,
            form:{
              fileId:null
            },
            tslId:null,
            formRules: {
              fileId:[{ validator:changeFile, trigger: 'blur' }]
            },
          }
      },
      methods:{
          show(tslId){
            this.tslId=tslId
            this.fileShow=false
            this.addBatchDeviceShow=true
          },
        fileChange(file,fileList){
          this.fileShow=true
        },
        beforeUpload(file){
          this.files = file;
          const extension = file.name.split('.')[1] === 'json'
          const isLt2M = file.size / 1024 / 1024 < 5
          if(!extension){
            this.$message.warning('仅支持json文件!')
            return
          }
          if (!isLt2M) {
            this.$message.warning('上传模板大小不能超过 5MB!')
            return
          }
          this.fileName = file.name;
          return false // 返回false不会自动上传
        },
        save() {
          var self = this
          this.$refs.addBatchDeviceForm.validate(result => {
            if(result){
              let fileFormData = new FormData();
              fileFormData.append('file', this.files, this.fileName);//filename是键，file是值，就是要传的文件，test.zip是要传的文件名
              let requestConfig = {
                headers: {
                  'Content-Type': 'multipart/form-data'
                },
              }
              this.$http.post(`${DataMainApi}/tsl/template/addDeviceExcel/${this.tslId}`, fileFormData, requestConfig).then((res) => {
                if (res.data.code === Status.success) {
                  self.$notify.success('保存成功')
                  self.addBatchDeviceShow = false
                  // 触发事件
                  self.$emit('success')
                } else {
                  self.$notify.error(res.data.message)
                }
                self.addBatchDeviceLoading = false
              }) .catch(() => {
                self.addBatchDeviceLoading = false
              })
            }
          });

        },
        downloadTemp: function () {
          var self = this
          self.$http({
            method: 'get',
            url: `${DataMainApi}/device/downloadTemplate/${this.type}`,
            responseType: 'arraybuffer'
          })
            .then((res) => {
              let a = document.createElement('a');
              let blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
              let objectUrl = URL.createObjectURL(blob);
              a.setAttribute("href",objectUrl);
              a.setAttribute("download", '物模型模板.json');
              a.click();
            })
        }
      }
    }
</script>

<style scoped>

</style>
